package dca.sistemascontrole.view.configuracao;

import br.ufrn.dca.controle.QuanserClientException;
import dca.sistemascontrole.driver.GerenciadorComunicacao;
import dca.sistemascontrole.driver.ServerConfig;
import dca.sistemascontrole.exception.LogManager;
import dca.sistemascontrole.util.ControleConstantes;
import dca.sistemascontrole.util.XMLManager;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JOptionPane;

/**
 *
 * @author Rafael
 */
public class DialogConfigurarPortas extends javax.swing.JDialog {

    private GerenciadorComunicacao gerenciadorComunicacao;

    public DialogConfigurarPortas(java.awt.Frame parent, boolean modal, GerenciadorComunicacao gerenciadorComunicacao) {
        super(parent, modal);
        initComponents();

        this.gerenciadorComunicacao = gerenciadorComunicacao;
        carregarUltimaConfig();
    }

    private void carregarUltimaConfig() {
        ServerConfig serverConfig = null;
        try {
            serverConfig = XMLManager.readObject(ControleConstantes.FILE_ROOT + ControleConstantes.FILE_CONFIGURACAO);
        } catch (FileNotFoundException ex) {
            LogManager.logErro(ex, "Não foi possível carregar a configuração das portas.");
        } catch (IOException ex) {
            LogManager.logErro(ex, "Não foi possível carregar a configuração das portas.");
        }

        if (serverConfig != null) {
            txtHost.setText(serverConfig.getHost());
            txtPorta.setText(serverConfig.getPorta() + "");
            txtCanalBomba.setText(serverConfig.getCanalBomba() + "");
            txtCanalTanqueSuperior.setText(serverConfig.getCanalTanqueSuperior() + "");
            txtCanalTanqueInferior.setText(serverConfig.getCanalTanqueInferior() + "");
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtHost = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPorta = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtCanalBomba = new javax.swing.JTextField();
        txtCanalTanqueSuperior = new javax.swing.JTextField();
        txtCanalTanqueInferior = new javax.swing.JTextField();
        btnConectar = new dca.sistemascontrole.view.components.CustomButton();
        btnCancelar = new dca.sistemascontrole.view.components.CustomButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Configurar portas");
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setText("Host:");

        jLabel2.setText("Porta:");

        jLabel3.setText("Canal Bomba:");

        jLabel4.setText("Canal Tanque Superior:");

        jLabel5.setText("Canal Tanque Inferior:");

        btnConectar.setBackground(new java.awt.Color(250, 250, 250));
        btnConectar.setText("Conectar");
        btnConectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConectarActionPerformed(evt);
            }
        });

        btnCancelar.setBackground(new java.awt.Color(250, 250, 250));
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtPorta, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
                            .addComponent(txtHost)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCanalBomba))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCanalTanqueSuperior, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(btnConectar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(txtCanalTanqueInferior, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE))))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel2});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel3, jLabel4, jLabel5});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPorta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(txtCanalBomba, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(txtCanalTanqueSuperior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(txtCanalTanqueInferior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnConectar, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel1, jLabel2, jLabel3, jLabel4, jLabel5, txtCanalBomba, txtCanalTanqueInferior, txtCanalTanqueSuperior, txtHost, txtPorta});

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnConectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConectarActionPerformed
        String host = txtHost.getText();
        if (host.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Host vázio.");
            return;
        }

        String porta = txtPorta.getText();
        if (!validarEntrada(porta)) {
            JOptionPane.showMessageDialog(this, "Porta inválida.");
            return;
        }

        String canalBomba = txtCanalBomba.getText();
        if (!validarEntrada(porta) || Integer.parseInt(canalBomba) < 0 || Integer.parseInt(canalBomba) > 7) {
            JOptionPane.showMessageDialog(this, "Canal para a bomba inválido.");
            return;
        }

        String canalTanqueInferior = txtCanalTanqueInferior.getText();
        if (!validarEntrada(porta) || Integer.parseInt(canalTanqueInferior) < 0 || Integer.parseInt(canalTanqueInferior) > 7) {
            JOptionPane.showMessageDialog(this, "Canal para o tanque inferior inválido.");
            return;
        }

        String canalTanqueSuperior = txtCanalTanqueSuperior.getText();
        if (!validarEntrada(porta) || Integer.parseInt(canalTanqueSuperior) < 0 || Integer.parseInt(canalTanqueSuperior) > 7) {
            JOptionPane.showMessageDialog(this, "Canal para o tanque Superior inválido.");
            return;
        }

        ServerConfig serverConfig = new ServerConfig(Integer.parseInt(porta), host, Integer.parseInt(canalBomba),
                Integer.parseInt(canalTanqueSuperior), Integer.parseInt(canalTanqueInferior));

        try {
            gerenciadorComunicacao.reloadService(serverConfig);
            
            JOptionPane.showMessageDialog(this, "Conectado com sucesso.");
            dispose();
        } catch (QuanserClientException ex) {
            JOptionPane.showMessageDialog(this, "Erro ao tentar criar o QuarserClient.");
            LogManager.logErro(ex, "Não foi possível iniciar o quarserClient.");
        }
    }//GEN-LAST:event_btnConectarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private boolean validarEntrada(String s) {
        try {
            Float.parseFloat(s);
        } catch (NumberFormatException ex) {
            return false;
        }

        return true;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private dca.sistemascontrole.view.components.CustomButton btnCancelar;
    private dca.sistemascontrole.view.components.CustomButton btnConectar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtCanalBomba;
    private javax.swing.JTextField txtCanalTanqueInferior;
    private javax.swing.JTextField txtCanalTanqueSuperior;
    private javax.swing.JTextField txtHost;
    private javax.swing.JTextField txtPorta;
    // End of variables declaration//GEN-END:variables
}
